<template>
	<view>
		<!-- <uni-nav-bar class="upload_logo" left-icon="arrowleft" color="white" rightIcon="home" title="添加全景" @click-left="back" backgroundColor="#393c43" @click-right="home"/>
		<view>
			<sunui-upbasic  :upImgConfig="upImgBasic" @onUpImg="upBasicData" @onImgDel="delImgInfo" ref="uImage" upTextDesc="hell">
				
			</sunui-upbasic>
		
			<button size="mini" class="publish_btn" type="primary" @tap="uImageTap">发布</button>
		</view> -->
		<uni-nav-bar left-icon="arrowleft" color="white" title="上传全景图" @click-left="back" backgroundColor="#cccccc" />
		<view class="upload flex flex-c">
			<text class="t">点击此处选择全景图</text>
			<text class="iconfont icon-shangchuan" @click="chooseImg"></text>
			<text class="tip">请上传2:1全景图仅支持JPG、JPEG格式 大小不超100MB</text>
		</view>

		<view class="list flex">
			<view class="item" v-for="(imgSrc, index) in imageArray" v-bind:key="imgSrc">
				<image :src="imgSrc" mode=""></image>
				<text :class="isupload[index]? 'up':'noup'">{{uploadInfo[index]}}</text>
				<text class="title">场景{{index+1}}</text>
				<text :class="!isupload[index] ? delIcon:''" @click="deleteThis(index)"></text>
			</view>
		</view>

		<view class="fb"><text @click="upload">发布</text></view>
		<uni-popup ref="popup" type="center" :custom="true">
			<view class="uploading">
				<cmd-progress type="circle" :percent="progressNum" background-color="red"></cmd-progress>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				delIcon: "iconfont icon-lajitong",
				basicArr: [],
				// 基础版配置
				upImgBasic: {
					// 后端图片接口地址
					basicConfig: {
						url: this.websiteUrl + '/api/upload/batch'
					},
					// 是否开启提示(提醒上传图片的数量)
					// tips: false,
					// 是否开启notli(开启的话就是选择完直接上传，关闭的话当count满足数量时才上传)
					notli: false,
					// 图片数量
					count: 2,
					// 相机来源(相机->camera,相册->album,两者都有->all,默认all)
					sourceType: 'camera',
					// 是否压缩上传照片(仅小程序生效)
					sizeType: true,
					// 上传图片背景修改
					upBgColor: '#E8A400',
					// 上传icon图标颜色修改(仅限于iconfont)
					upIconColor: '#fff',
					upTextDesc: '选择全景图',
					// 上传svg图标名称
					// upSvgIconName: 'icon-card',
					// 上传文字描述(仅限四个字)
					// upTextDesc: '上传证书',
					// 删除按钮位置(left,right,bleft,bright),默认右上角
					delBtnLocation: '',
					// 是否隐藏添加图片
					// isAddImage: false,
					// 是否隐藏删除图标
					// isDelIcon: false,
					// 删除图标定义背景颜色
					// delIconColor: '',
					// 删除图标字体颜色
					// delIconText: '',
					// 上传图标替换(+),是个http,https图片地址(https://www.playsort.cn/right.png)
					iconReplace: '',
					projectId: 0
				},
				imageArray: [],
				progressNum: 0,
				cellphone: '',
				uploadInfo: [],
				isupload: [],
				uploadIndex: 0
			};
		},
		onLoad: function(option) {
			this.projectId = (option.id == undefined ? 0 : option.id);
			uni.getStorage({
				key: 'cellphone',
				success: function(res) {

				},
				fail: function(res) {
					uni.navigateTo({
						url: "../login/index"
					})
				}
			});
		},
		methods: {
			// 手动上传图片(适用于表单等上传) -2019/05/10增加
			uImageTap() {
				this.$refs.uImage.uploadimage(this.upImgBasic);
			},
			// 删除图片 -2019/05/12(本地图片进行删除)
			async delImgInfo(e) {
				// console.log('你删除的图片地址为:', e, this.basicArr.splice(e.index, 1));
			},
			// 基础版
			async upBasicData(e) {
				// console.log('===>', e);
				// 上传图片数组
				let arrImg = [];
				for (let i = 0, len = e.length; i < len; i++) {
					try {
						if (e[i].path_server != '') {
							await arrImg.push(e[i].path_server.split(','));
						}
					} catch (err) {
						console.log('上传失败...');
					}
				}
				// 图片信息保存到data数组
				this.basicArr = arrImg;

				// 可以根据长度来判断图片是否上传成功. 2019/4/11新增
				if (arrImg.length == this.upImgBasic.count) {
					uni.showToast({
						title: `上传成功`,
						icon: 'none'
					});
				}
			},
			// 获取上传图片basic
			getUpImgInfoBasic() {
				// console.log('后端转成一维数组:', this.basicArr.join().split(','));
			},
			back: function() {
				uni.switchTab({
					url: '../user/index'
				});
			},
			home: function() {
				uni.switchTab({
					url: '../index/index'
				});
			},
			chooseImg: function() {
				uni.chooseImage({
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: chooseImageRes => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						for (var i = 0; i < tempFilePaths.length; i++) {
							this.imageArray.push(tempFilePaths[i]);
							this.uploadInfo.push("未上传");
							this.isupload.push(false);

						}
					}
				});
			},
			deleteThis: function(index) {
				var temArray = [];
				for (var i = 0; i < this.imageArray.length; i++) {
					if (i != index) {
						temArray.push(this.imageArray[i]);
					}
				}
				this.imageArray = temArray;
				this.uploadInfo[index] = "未上传";
				this.isupload[index] = false;
				if (this.uploadIndex > 0) {
					this.uploadIndex--;
				}

			},
			randomStr: function(len) {
				len = len || 32;
				var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
				var maxPos = $chars.length;
				var pwd = '';
				for (var i = 0; i < len; i++) {
					pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			},
			upload: function() {
				this.bsuccess = true;
				var that = this;
				var cellphone;
				uni.getStorage({
					key: 'cellphone',
					success: function(res) {
						cellphone = res.data;
					},
					fail: function(res) {
						uni.navigateTo({
							url: "../login/index"
						})
					}
				});
				var folderStr = this.randomStr(10);
				var times = 0;
				for (var i = 0; i < this.imageArray.length; i++) {

					const uploadTask = uni.uploadFile({
						url: this.websiteUrl + '/api/upload/batch', //仅为示例，非真实的接口地址
						filePath: this.imageArray[i],
						name: 'file',
						formData: {
							"cellphone": cellphone,
							'projectId': this.projectId,
							'folder': folderStr
						},
						success: uploadFileRes => {
							times++;
							var project_id = this.projectId;
							if (times == 1) {
								setTimeout(function() {
									that.closePopup();
								}, 3000);
								uni.request({
									url: this.websiteUrl + '/api/compound_panorama',
									header: {
										'content-type': 'application/x-www-form-urlencoded'
									},
									data: {
										"project_id": project_id,
										"num": i
									},
									method: "POST",
									success: (resp) => {
										console.log(resp.data)
										uni.showLoading({
											title: "后台正在合成全景"
										})
										var timer = setInterval(function() {
											uni.request({
												url: that.websiteUrl + '/api/background_processing',
												data: {
													"project": project_id
												},
												method: "POST",
												header: {
													'content-type': 'application/x-www-form-urlencoded'
												},
												success: (resp) => {
													console.log(resp);
													if (resp.data.data) {
														uni.hideLoading();
														clearInterval(timer);
														uni.showToast({
															title:"合成成功"
														})
														setTimeout(function(){
															uni.navigateTo({
																url:"../krpano/krpano?project_id="+that.projectId
															})
														},2000);
													}
												}
											})

										}, 1000)
									}
								});
							}
						},
						fail: (res) => {
							uni.showToast({
								title: "上传失败",
								image: "../../static/image/failed.png"
							})
						}
					});
					uploadTask.onProgressUpdate(res => {
						// console.log('上传进度' + res.progress);
						// console.log('已经上传的数据长度' + res.totalBytesSent);
						// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

						if (isNaN(res.progress)) {
							uploadTask.abort();
						} else {
							this.progressNum += res.progress;
							if (res.progress == 100) {
								this.uploadInfo[this.uploadIndex] = "已上传";
								this.isupload[this.uploadIndex] = true;
								this.uploadIndex++;
							}
							this.openPopup();
						}

					});
				}
			},
			openPopup() {
				this.$refs.popup.open()
			},
			closePopup() {
				this.$refs.popup.close()
			}
		}
	};
</script>

<style>
	@import url('../../common/common.css');

	page {
		background-color: white;
	}

	.publish_btn {
		width: 300rpx;
		position: absolute;
		bottom: 30rpx;
		border-radius: 30rpx;
		left: 50%;
		display: block;
		margin: 0 -150rpx 30rpx;
		background-color: #10a408;
	}

	.upload_logo {
		width: 100%;
	}

	.sunsin_picture_list[data-v-1f32ce40] {
		width: 100%;
	}

	.upload {
		background: #393c43;
		color: #fff;
		align-items: center;
	}

	.upload .t {
		font-size: 32rpx;
		margin: 20rpx 0 30rpx;
	}

	.upload .iconfont {
		font-size: 120rpx;
	}

	.upload .tip {
		margin: 30rpx 0 20rpx;
		color: #d71619;
	}

	.list {
		padding: 0 20rpx 100rpx;
		flex-wrap: wrap;
	}

	.item {
		width: 345rpx;
		height: 200rpx;
		position: relative;
		border-radius: 10rpx;
		margin: 20rpx 20rpx 0 0;
	}

	.item:nth-of-type(2n) {
		margin-right: 0;
	}

	.item image {
		width: 345rpx;
		height: 200rpx;
	}

	.item .noup {
		position: absolute;
		background: #ff4444;
		color: #fff;
		font-size: 24rpx;
		line-height: 40rpx;
		padding: 0 10rpx;
		border-radius: 20rpx;
		top: 10rpx;
		left: 10rpx;
	}

	.item .up {
		position: absolute;
		background: #44ff44;
		color: #fff;
		font-size: 24rpx;
		line-height: 40rpx;
		padding: 0 10rpx;
		border-radius: 20rpx;
		top: 10rpx;
		left: 10rpx;
	}

	.item .iconfont {
		color: #ff4444;
		background: rgba(0, 0, 0, 0.6);
		position: absolute;
		top: 0;
		right: 0;
		font-size: 36rpx;
		text-align: center;
		width: 60rpx;
		line-height: 60rpx;
	}

	.item .title {
		color: #fff;
		font-size: 24rpx;
		position: absolute;
		bottom: 0;
		left: 0;
		width: 325rpx;
		text-align: center;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
		padding: 10rpx;
	}

	.fb {
		position: fixed;
		width: 100%;
		bottom: 0;
		height: 100rpx;
		background: #393c43;
	}

	.fb text {
		display: inline-block;
		width: 300rpx;
		height: 60rpx;
		line-height: 60rpx;
		color: #fff;
		font-size: 24rpx;
		text-align: center;
		background: #10a408;
		margin: 20rpx 225rpx;
		border-radius: 30rpx;
	}

	.uploading {
		background-color: rgba(0, 0, 0, 0);
	}

	.uploading text {
		background-color: rgba(0, 0, 0, 0);
	}
</style>
